package zuul.config;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class CloudZuulFilter extends ZuulFilter {

    /**
     * 在请求之前或之后执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
        /*return "post";
        return "after";*/
    }

    /**
     * 执行顺序，越小越先执行
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 是否开启过滤器
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器执行的操作
     *
     * @return
	 */
    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
		// 如果为options请求则一定要返回200状态码
		if ("options".equals(currentContext.getRequest().getMethod().toLowerCase())) {
			currentContext.setSendZuulResponse(false);
			currentContext.setResponseStatusCode(HttpStatus.OK.value());
			return null;
		}
        HttpServletRequest request = currentContext.getRequest();

        //登录不拦截
        if (request.getRequestURI().indexOf("login") > 0) {
            return null;
        }
        //经过网关头信息会丢失，如果存在需要传送的头信息在这里转发一下头信息
        String header = request.getHeader("token");
        if (header != null && !"".equals(header)) {
            //转发头信息
            currentContext.addZuulRequestHeader("token", header);
        }

        return null;
    }
}
